<template>
  <view class="container">
    <!-- 聊天主区域 -->
    <view class="chat-main">
      <!-- 消息容器 -->
      <scroll-view class="messages-container" scroll-y="true" :scroll-top="scrollTop">
        <view 
          v-for="message in messages" 
          :key="message.id" 
          :class="['message', message.isUser ? 'user-message' : 'ai-message']"
        >
          <view class="message-content">
            <view class="avatar">
              <image :src="message.isUser ? avatarBoy : qqIcon" mode="aspectFill"></image>
            </view>
            <view class="text-content">
              <view class="text">{{ message.text }}</view>
            </view>
          </view>
        </view>
        <!-- 加载指示器 -->
        <view v-if="isLoading" class="message ai-message">
          <view class="message-content">
            <view class="avatar">
              <image :src="qqIcon" mode="aspectFill"></image>
            </view>
            <view class="text-content">
              <view class="text">正在思考中...</view>
            </view>
          </view>
        </view>
      </scroll-view>
      
      <!-- 输入区域 -->
      <view class="input-container">
        <view class="input-wrapper">
          <input 
            class="message-input" 
            placeholder="输入消息..." 
            v-model="newMessage" 
            @confirm="sendMessage" 
            :disabled="isLoading"
          />
          <button class="send-button" @click="sendMessage" :disabled="!newMessage.trim() || isLoading">
            发送
          </button>
        </view>
      </view>
    </view>

    <tabBar :current="current"></tabBar>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import tabBar from '../../components/tabBar/tabBar.vue'

// 引入静态资源
const avatarBoy = '../../static/images/avatar.png'
const qqIcon = '../../static/images/icon/icon-index-video.png'

// 当前tabbar索引
const current = ref(0)

// 聊天相关数据
const newMessage = ref('')
const messages = ref([
  { id: 1, text: '您好！我是AI助手，有什么可以帮助您的吗？', isUser: false }
])
const isLoading = ref(false)
const scrollTop = ref(0)
const sessionId = ref('')
const eventSource = ref(null)

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  //获取当前tabbar的值
  getCurrentId()
  // 初始化sessionId
  sessionId.value = generateSessionId()
  // 初始化SSE连接
  initSSE()
})

onUnmounted(() => {
  // 组件销毁前关闭SSE连接
  if (eventSource.value) {
    eventSource.value.close()
  }
})

const getCurrentId = () => {  
  const tabBarObj = uni.getStorageSync('tabbar')
  // 获取当前页面栈的实例
  let pages = getCurrentPages();
  // 获取当前页面的路由
  let currentPage = pages[pages.length - 1];
  for(var i in tabBarObj){
    if(tabBarObj[i].url == "/"+currentPage.route){
      current.value = i;
    }
  }
}

// 生成会话ID
const generateSessionId = () => {
  return 'session_' + Math.random().toString(36).substr(2, 9);
}

// 初始化SSE连接
const initSSE = () => {
  // 注意：这里需要替换为实际的API地址
  const baseUrl = import.meta.env.VITE_APP_BASE_API // 根据实际情况配置
  const url = `${baseUrl}/ai/stream/${sessionId.value}`
  
  // 由于目前没有实际的后端服务，暂时注释掉SSE连接
  
  // 创建EventSource连接
  eventSource.value = new EventSource(url)
  
  // 监听连接事件
  eventSource.value.addEventListener('connect', (event) => {
    try {
      const data = JSON.parse(event.data)
      addMessage(data)
    } catch (e) {
      console.error('Error parsing connect event data:', e)
    }
  })
  
  // 监听消息事件
  eventSource.value.addEventListener('message', (event) => {
    try {
      const data = JSON.parse(event.data)
      if (!data.isUser) {
        // 更新最后一条消息或添加新消息
        const lastMessage = messages.value[messages.value.length - 1]
        // 检查是否是同一批消息的一部分
        if (lastMessage && !lastMessage.isUser && !lastMessage.completed) {
          // 更新现有消息内容
          lastMessage.text = (lastMessage.text || '') + (data.content || '')
        } else {
          // 添加新消息
          addMessage({
            text: data.content || data.text || event.data,
            isUser: false,
            id: messages.value.length + 1,
            completed: false
          })
        }
        nextTick(() => {
          scrollToBottom()
        })
      }
    } catch (e) {
      console.error('Error parsing message event data:', e)
      // 即使解析出错也显示原始数据
      addMessage({
        text: event.data,
        isUser: false,
        id: messages.value.length + 1,
        completed: false
      })
    }
  })
  
  // 监听完成事件
  eventSource.value.addEventListener('complete', (event) => {
    try {
      const data = JSON.parse(event.data)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && !lastMessage.isUser) {
        lastMessage.completed = true
      }
    } catch (e) {
      console.error('Error parsing complete event data:', e)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && !lastMessage.isUser) {
        lastMessage.completed = true
      }
    }
    isLoading.value = false
  })
  
  // 错误处理
  eventSource.value.onerror = (error) => {
    console.error('SSE连接错误:', error)
    isLoading.value = false
    // 确保在错误时也能正确处理
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && !lastMessage.isUser && !lastMessage.text) {
      lastMessage.completed = true
    } else if (!lastMessage || lastMessage.isUser) {
      // 如果没有消息或最后一条是用户消息，则添加错误消息
      addMessage({
        text: "抱歉，连接服务器时出现问题，请稍后再试。",
        isUser: false,
        id: messages.value.length + 1,
        completed: true
      })
    }
  }
  
}

// 添加消息到列表
const addMessage = (message) => {
  messages.value.push(message)
  nextTick(() => {
    scrollToBottom()
  })
}

// 滚动到底部
const scrollToBottom = () => {
  // 使用nextTick确保DOM更新完成后再滚动
  nextTick(() => {
    scrollTop.value = 999999 // 设置一个足够大的值以确保滚动到底部
  })
}

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim() && !isLoading.value) {
    // 添加用户消息
    const userMessage = { 
      text: newMessage.value, 
      isUser: true, 
      id: messages.value.length + 1 
    }
    addMessage(userMessage)
    
    // 保存当前消息
    const userQuery = newMessage.value
    newMessage.value = ''
    
    // 获取AI响应
    getAIResponse(userMessage.id, userQuery)
  }
}

// 获取AI响应
const getAIResponse = (messageId, userQuery) => {
  isLoading.value = true
  
  // 模拟AI响应
  setTimeout(() => {
    const responses = [
      "你好！我是一个AI助手，我可以帮助你解答各种问题。",
      "这是一个很好的问题！让我来为你详细解释一下。",
      "根据你的问题，我建议你可以尝试以下几种解决方案。",
      "我不太确定你的具体需求，你能提供更多细节信息吗？",
      "这个问题涉及到多个方面，我会逐一为你分析。",
      "感谢你的提问，我很乐意为你提供帮助。"
    ]
    
    const randomResponse = responses[Math.floor(Math.random() * responses.length)]
    
    addMessage({
      text: randomResponse,
      isUser: false,
      id: messages.value.length + 1
    })
    
    isLoading.value = false
  }, 1000)
  
  
  try {
    // 这里应该调用实际的API接口发送用户消息
    // 注意：在uni-app中需要使用uni.request而不是axios
    const baseUrl = import.meta.env.VITE_APP_BASE_API  // 根据实际情况配置
    
    uni.request({
      url: `${baseUrl}/ai/send?sessionId=`+sessionId.value+'&user=用户&message='+userQuery,
      method: 'POST',
      data: {
        memoryId: '',
        message: userQuery,
        sessionId: sessionId.value,
        user: '用户'
      },
      success: (res) => {
        // 不需要在这里处理响应，因为SSE事件监听器会处理
        console.log('消息发送成功')
      },
      fail: (err) => {
        console.error('发送消息失败:', err)
        isLoading.value = false
      }
    })
  } catch (error) {
    console.error('Error getting AI response:', error)
    isLoading.value = false
    // 显示错误消息给用户
    const errorMessage = { 
      text: "抱歉，发送消息时出现问题，请稍后再试。", 
      isUser: false, 
      id: messages.value.length + 1 
    }
    addMessage(errorMessage)
  }
  
}

/**
 * 去登陆
 */
const toLogin = () => {
  uni.navigateTo({
    url: '/pages/accountLogin/accountLogin'
  })
}

</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 50px; /* 为tabBar预留空间 */
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding-bottom: 16px; /* 为输入框预留空间 */
}

.messages-container {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 16px;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.message-content {
  display: flex;
  align-items: flex-start;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 8px;
}

.avatar image {
  width: 100%;
  height: 100%;
}

.text-content {
  max-width: calc(100% - 48px);
}

.user-message .text-content {
  text-align: right;
}

.text {
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
}

.ai-message .text {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-top-left-radius: 4px;
}

.user-message .text {
  background-color: #007AFF;
  color: white;
  border-top-right-radius: 4px;
}

.input-container {
  padding: 16px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 20px;
  padding: 8px 16px;
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 8px 0;
  font-size: 16px;
  outline: none;
}

.message-input:disabled {
  opacity: 0.6;
}

.send-button {
  background: transparent;
  border: none;
  cursor: pointer;
  padding: 8px;
  color: #007AFF;
  font-size: 14px;
}

.send-button:disabled {
  color: #cccccc;
  cursor: not-allowed;
}
</style>